<?php

define('__SQL_MODE_LIST',  0);
define('__SQL_MODE_COUNT', 1);

class guest_book extends module 
{

#---------------------------------------------------------------------------------	

	var $submit 	= false;
	var $name		= '';
	var $email		= '';
	var $title		= '';
	var $message	= '';
	var $path_tmpl	= '';

#---------------------------------------------------------------------------------			
		
	function GetFormJSField($data_mass, $end_name)
	{
		$res = '';
		
		if ( is_array($data_mass) )
		{
			$keys = array_keys($data_mass);
			$index = sizeof($keys);
			for($i=0; $i<$index; $i++)
			{
				if( eregi( $end_name.'$', $keys[$i] ) )
				{
					$res = $data_mass[$keys[$i]];
					break;
				}
			}
		}	
	
		return $res;
	}
		
#---------------------------------------------------------------------------------	

	function content_init()
	{	
		global $common_data_server;
		
		$this->path_tmpl = $common_data_server."module_templates/".get_class($this)."/".$this -> view_param['template']."/";
		$this->submit = isset($this->q_param['sub']) ? true : false;
		$error = false;
		
		if ( $this->submit )
		{
			$this->name 	= htmlspecialchars( trim( $this->GetFormJSField( $this->q_param, 'name'  ), ENT_QUOTES));
			$this->email 	= htmlspecialchars( trim( $this->GetFormJSField( $this->q_param, 'email' ), ENT_QUOTES));
			$this->title 	= htmlspecialchars( trim( $this->GetFormJSField( $this->q_param, 'title' ), ENT_QUOTES));
			$this->message 	= htmlspecialchars( trim( strip_tags($this->GetFormJSField( $this->q_param, 'message' )), ENT_QUOTES));
			
			#check errors
			if ( !$this->name )
			{
				$err_name = 1;
				$error = true;
			}
			
			if ( $this->email && !$this->check_email($this->email) )
			{
				$err_email = 1;
				$error = true;
			}
			
			if ( !$this->title )
			{
				$err_title = 1;
				$error = true;
			}
			
			if ( !$this->message )
			{
				$err_message = 1;
				$error = true;
			}
			
			#добавляем запись
			if ( !$error )
			{
				insert_record(
								'GUEST_BOOK',
								 array(
								 		array('name' => 'VERSION', 		'value' => '1' ),
								 		array('name' => 'LANG_ID', 		'value' => $this->lang_id ),
								 		array('name' => 'STATE_ID',		'value' => $this->GetState() ),
								 		array('name' => 'TIME_STAMP',	'value' => time() ),
								 		array('name' => 'TITLE',		'value' => $this->title ),
								 		array('name' => 'DATE_TIME',	'value' => date("YmdHis") ),
								 		array('name' => 'NAME',			'value' => $this->name ),
								 		array('name' => 'EMAIL',		'value' => $this->email ),
								 		array('name' => 'MESSAGE',		'value' => $this->message, 'type' => 'BLOB' ),
								 )
							);
							
				$insert_id = intval( $this->GetInsertID() );
				
				if ( $insert_id )
				{
					insert_record(
									'CONTENT_MAP',
									array(
											array('name' => 'INF_BLOCK_ID', 'value' => $this->block_id ),
											array('name' => 'CONTENT_ID', 'value' => $insert_id),
											array('name' => 'IS_MAIN', 'value' => '1'),
									)
								); 
								
					#отправляем письмо администратору
					if ( $this->view_param['adm_email'] )
					{
						if ( file_exists($this->path_tmpl.'mail.vtmpl') )
						{
							$tmpl_mail = & new vlibTemplate($this->path_tmpl.'mail.vtmpl'); 
							$tmpl_mail->setVar('NAME',		$this->name);
							$tmpl_mail->setVar('EMAIL',		$this->email);
							$tmpl_mail->setVar('TITLE',		$this->title);
							$tmpl_mail->setVar('MESSAGE',	$this->message);
							$tmpl_mail->setVar('IP',		$_SERVER['REMOTE_ADDR']);
							$message = $tmpl_mail->grab();
							unset($tmpl_mail);
							
							post_mail(
										$this->view_param['adm_email'],
										'Администратору сайта '.$_SERVER['HTTP_HOST'],
										$_SERVER['SERVER_ADMIN'],
										$_SERVER['HTTP_HOST'],
										'Гостевая книга',
										$message
									);
						}			
					}
				}							
			
				header("Location: http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?is_send'.$this->tarea_id.'=1');
			}
		}
		
		#navigation
		$count_vopr = sql_select( $this->MakeSQL(__SQL_MODE_COUNT) );
		if ( $count_vopr[0]['COUNT'] > 1 )
		{
			$nav = page_navigation($this->view_param['num_per_page'], $count_vopr[0]['COUNT'], "from".$this->tarea_id, $this->path_tmpl."nav.vtmpl");
		}	
		#end navigation	
		
		$query = $this->MakeSQL();
		$vopr = sql_select($query);
		
		$template = $this->path_tmpl.'list.vtmpl';
		
		if( file_exists($template) )
        {
			$tmpl = & new vlibTemplate($template);
			
			$tmpl->setVar('NAVIGATION', 	$nav);
			$tmpl->setVar('IS_SEND', 		$this->q_param['is_send']);
			$tmpl->setVar('err_email',		$err_email);
			$tmpl->setVar('err_name',		$err_name);
			$tmpl->setVar('err_title',		$err_name);
			$tmpl->setVar('err_message',	$err_message);
			$tmpl->setVar('NAME',			$this->name);
			$tmpl->setVar('EMAIL',			$this->email);
			$tmpl->setVar('TITLE',			$this->title);
			$tmpl->setVar('MESSAGE',		$this->message);
			$tmpl->setVar('tarea_id',		$this->tarea_id);
			
			$tmpl->setLoop('GB_LOOP',		$vopr); 
			
			$this->body .= $tmpl->grab();	
			unset($tmpl);
        }
        else $this->body .= 'Can\'t find template file: '.$template;	
	}
	
#------------------------------------------------------------------------------------------

	function GetInsertID()
	{
		$vopr = sql_select("SELECT 
									MAX(CONTENT_ID) AS MAX_COUNT 
							FROM 
									GUEST_BOOK");
		
		return intval( $vopr[0]['MAX_COUNT'] );
	}

#------------------------------------------------------------------------------------------

    function check_email( $val )
    {
         $res = false;
            
     	 $mask =   '^([a-zA-Z0-9_]|-|.)+'.
                   '@'.
                   '([a-zA-Z0-9_]|-|.)+'.
                   '[a-zA-Z]{2,4}$';
       
         $res = eregi( $mask, $val );

         return $res;
    } 
        	
#---------------------------------------------------------------------------------	

	function MakeSQL( $mode = __SQL_MODE_LIST )
	{
		$limit = '';
		
		if ( $mode == __SQL_MODE_LIST )
		{
			$from = $this->q_param["from"] - 1;
			if( intval($from) < 0 ) $from = 0;
			$limit = ' LIMIT '.(string)($from*$this->view_param['num_per_page']).','.(string)($this->view_param['num_per_page'])." ";
		}

		$query = "	SELECT
							".( ( $mode == __SQL_MODE_LIST ) ? " * " : " COUNT( DISTINCT GB.CONTENT_ID ) AS COUNT ")."
					FROM
							GUEST_BOOK GB,
							CONTENT_MAP CM
					WHERE
							CM.INF_BLOCK_ID 		= ".intval($this -> block_id)." and 
							GB.CONTENT_ID 			= CM.CONTENT_ID and
	    					GB.VERSION 				= ".intval($this -> version)." and
    						GB.LANG_ID 				= ".intval($this -> lang_id)." 
    				ORDER BY
    						GB.DATE_TIME DESC".
					$limit;

		return $query;
	}
	
#---------------------------------------------------------------------------------	

	function GetState()
	{
		$res = 0;
		
		$query = "	SELECT
							NEW_STATE_ID
					FROM
							LANG
					WHERE
							LANG_ID = ".intval($this->lang_id);
		
		$vopr = sql_select($query);
		$res = intval($vopr[0]['NEW_STATE_ID']);
		
		return $res;
	}

#---------------------------------------------------------------------------------	

	function get_hash_code()
	{
		return 0;
	}
	
#---------------------------------------------------------------------------------	

}#end class guest_book